package com.fenye.testflow.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.fenye.testflow.model.vo.ValidateCodeVo;
import com.fenye.testflow.service.ValidateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class ValidateServiceImpl implements ValidateService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode() {
        // 使用hutool工具包中的工具类生成图片验证码
        //参数：宽  高  验证码位数 干扰线数量
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(100, 30, 4, 2);
        String codeValue = circleCaptcha.getCode();
        String imageBase64 = circleCaptcha.getImageBase64();

        // 生成uuid作为图片验证码的key
        String codeKey = UUID.randomUUID().toString().replace("_", "");
        // 将验证码存储到Redis中
        redisTemplate.opsForValue().set("user:login:validatecode:"+codeKey,codeValue);
        // 构建响应结果数据
        ValidateCodeVo vo = new ValidateCodeVo();
        vo.setCodeValue("data:image/png;base64," + imageBase64);
        vo.setCodeKey(codeKey);
        return vo;
    }
}
